<!-- 
 https://lbs.amap.com/demo/amap-ui/demos/amap-ui-pathsimplifier/navigators
 重点参数： renderOptions -->
<!doctype html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>轨迹巡航控制</title>
    <style>
        #trajectoryMapContainer,
        body,
        html {
            height: 100%;
            width: 100%
        }

        #loadingTip,
        #panel {
            position: absolute;
            top: 0
        }

        body,
        html {
            margin: 0;
            font-size: 12px
        }

        #outer-box {
            height: 100%;
            padding-right: 300px;
        }

        #panel {
            right: 0;
            width: 300px;
            z-index: 999;
            height: calc(100% - 5px);
            overflow: hidden;
            overflow-y: auto
        }



        #loadingTip {
            z-index: 9999;
            left: 0;
            padding: 3px 10px;
            background: red;
            color: #fff;
            font-size: 13px
        }

        .route-item {
            margin-bottom: 10px
        }

        .route-item pre {
            margin: 0
        }

        .route-item h3 {
            margin: 5px 0;
            font-size: 14px;
            cursor: pointer
        }

        .hide {
            display: none
        }

        .speedBox {
            padding: 5px 0
        }

        .speedRange {
            vertical-align: middle;
            margin: 0;
            padding: 0;
            width: 100px
        }

        .markerInfo {
            /* background: rgba(255, 255, 255, 0.7); */
            background: red;
            padding: 2px 5px;
            border: 1px solid #ccc;
            white-space: nowrap;
        }
    </style>
</head>

<body>
    <div id="outer-box">
        <div id="trajectoryMapContainer">
        </div>
        <div id="panel">
            操作按钮
            <div class="control-buttons">
                <button id="btnControl">开始</button>

                <!-- <button id="btnStart">开始巡航</button>
                <button id="btnPause">暂停</button>
                <button id="btnResume">恢复</button>
                <button id="btnStop">停止</button>
                <button id="btnDestroy">销毁</button> -->
            </div>

            显示状态信息
            <div id="statusInfo" style="margin-top:10px;"></div>

            <!-- 速度选择 -->
            <label for="speedSelect" id="speedLabel">X1</label>
            <select id="speedSelect">
                <option value="0.5">0.5x</option>
                <option value="1" selected>1x</option>
                <option value="2">2x</option>
                <option value="4">4x</option>
                <option value="8">8x</option>
                <option value="32">32x</option>
                <option value="64">64x</option>
            </select>



        </div>


    </div>
    <script src="https://webapi.amap.com/maps?v=2.0&key=6089b5b868160cd9820c162d02c1e10c"></script>
    <script src="https://webapi.amap.com/ui/1.1/main.js"></script>
    <script src="/lib/layui-v2.11.4/layui.js" charset="utf-8"></script>

    <script type="text/javascript">
        layui.use(['form'], function () {
            var $ = layui.$;

            //创建地图
            var map = new AMap.Map('trajectoryMapContainer', {
                zoom: 14
            });

            initAMapUI()
            //起点
            var startMarker = null;
            //终点
            var endMarker = null;
            var pathSimplifierIns = null;

            var path = [];
            /** 1、创建地图UI*/
            function initAMapUI() {
                AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) {
                    if (!PathSimplifier.supportCanvas) {
                        alert('当前环境不支持 Canvas！');
                        return;
                    }

                    var pathLineStyle = {
                        strokeStyle: '#28F',
                        lineWidth: 6,
                        borderStyle: '#fff',
                        borderWidth: 1
                    };
                    var pathLineHoverStyle = {
                        strokeStyle: '#2288ffb2',
                        lineWidth: 6,
                        borderStyle: '#fff',
                        borderWidth: 1
                    };
                    var emptyLineStyle = {
                        lineWidth: 0,
                        fillStyle: null,
                        strokeStyle: null,
                        borderStyle: null
                    };

                    pathSimplifierIns = new PathSimplifier({
                        zIndex: 100,
                        //是否在绘制后自动调整地图视野以适合全部轨迹，默认true。
                        autoSetFitView: true,
                        map: map, //所属的地图实例
                        getPath: function (pathData, pathIndex) {
                            return pathData.path;
                        },
                        getHoverTitle: function (pathData, pathIndex, pointIndex) {

                            return null;
                        },
                        renderOptions: {
                            pathLineStyle: {
                                dirArrowStyle: true
                            },
                            getPathStyle: function (pathItem, zoom) {
                                return {
                                    pathLineStyle: pathLineStyle,
                                    pathLineSelectedStyle: pathLineStyle,
                                    pathLineHoverStyle: pathLineHoverStyle,
                                    keyPointStyle: emptyLineStyle,
                                    startPointStyle: emptyLineStyle,
                                    endPointStyle: emptyLineStyle,
                                    keyPointHoverStyle: emptyLineStyle,
                                    keyPointOnSelectedPathLineStyle: emptyLineStyle
                                };
                            }
                        }
                    });
                    afterMapMount();
                });
            }
            /* 2、地图加载完成后执行*/
            function afterMapMount() {
                window.pathSimplifierIns = pathSimplifierIns;
                $.getJSON('/api/trackList.json', function (d) {
                    path = d.data.map(function (item) {
                        return [item.longitude, item.latitude];
                    });

                    let carAlarmPaths = [{ name: '轨迹', path }]
                    pathSimplifierIns.setData(carAlarmPaths);
                });
            }

            var pathNavigs = null;
            const BASE_SPEED = 500;//默认速度
            var navgIndex = -1;//巡航索引
            // 创建巡航
            function createNavg() {

                if (!pathNavigs) {
                    // 创建路径导航器
                    var navgtr = pathSimplifierIns.createPathNavigator(0, {
                        loop: false,
                        speed: BASE_SPEED
                    });

                    navgtr.marker = new AMap.Marker({
                        offset: new AMap.Pixel(12, -10),
                        map: map
                    });

                    var $msg = $('#statusInfo');

                    navgtr.on('move', function (e) {


                        var targetIndex = e.target.getCursor().idx;
                        var lnglat = e.target.getPosition();
                        if (navgIndex === targetIndex) {
                            console.error('same index')
                            return;
                        }
                        navgIndex = targetIndex;

                        console.log('navgIndex==', navgIndex)
                        navgtr.marker.setPosition(navgtr.getPosition());
                        // this.timeSliderPosition = this.path[this.navgIndex];
                        // // 更新时间轴
                        // document.getElementById('timeSlider').value = this.navgIndex;
                        // document.getElementById('timeDisplay').textContent =
                        //     this.originDetailData[this.navgIndex].time;


                        // 最后一个点结束
                        var originListLength = path.length - 1;
                        if (targetIndex === originListLength) {
                            navgIndex = -1;
                            // this.initEndMarker();
                            setNavgEnd();
                        }


                        // console.log('move=====')

                    });

                    navgtr.onDestroy(function () {
                        console.log('onDestroy=====')
                        pathNavigs = null;
                        navgtr.marker.setMap(null);
                        $msg.html('');
                        updateButtonStates();
                    });

                    navgtr.on('start resume', function () {
                        console.log('start resume=====')
                        navgtr._startTime = Date.now();
                        navgtr._startDist = this.getMovedDistance();
                    });

                    navgtr.on('stop pause', function () {
                        console.log('stop pause=====', this.getNaviStatus())
                        navgtr._movedTime = Date.now() - navgtr._startTime;
                        updateButtonStates(); // 更新按钮状态
                        var msgInfo = {
                            '状态': this.getNaviStatus(),
                            '设定速度': this.getSpeed() + ' km/h',
                            '本段耗时': (navgtr._movedTime / 1000) + ' s'
                        };

                        $msg.html('<pre>' + JSON.stringify(msgInfo, null, 2) + '</pre>');
                    });

                    navgtr.on('move', function () {
                        console.log('move=====', this.getNaviStatus())
                        var msgInfo = {
                            '状态': this.getNaviStatus(),
                            '设定速度': this.getSpeed() + ' km/h',
                        };
                        $msg.html('<pre>' + JSON.stringify(msgInfo, null, 2) + '</pre>');
                    });

                    navgtr.on('end', function () {
                        console.log('end=====轨迹播放已完成')
                        updateButtonStates(); // 更新按钮状态
                    });


                    pathNavigs = navgtr;

                    updateButtonStates(); // 初始化按钮状态
                    updateSpeedFromSelect(); // 初始化速度
                }

                return pathNavigs;
            }

            // 初始化所有marker和轨迹
            function initMarker() {
                // 画出起点marker
                startMarker = new AMap.Marker({
                    map: map,
                    position: path[0],
                    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
                    // size: new window.AMap.Size(48, 48),
                    // position: this.pointList[0],
                    // icon: __webpack_require__("1634"),
                    // offset: new window.AMap.Pixel(-21, -45),
                    // zIndex: 70
                });
            }
            function initEndMarker() {
                // 画出终点的marker
                endMarker = new AMap.Marker({
                    map: map,
                    position: path[path.length - 1],
                    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
                    // size: new window.AMap.Size(48, 48),
                    // position: this.pointList[this.pointList.length - 1],
                    // icon: __webpack_require__("4590"),
                    // offset: new window.AMap.Pixel(-21, -45),
                    // zIndex: 70
                });
            }
            // 设置为结束状态
            function setNavgEnd() {
                if (pathNavigs) pathNavigs.destroy();
                pathNavigs = null;
                updateButtonStates();

            }
            /**
             * 更新速度
             */
            function updateSpeedFromSelect() {
                const multiplier = parseFloat($('#speedSelect').val());
                const speed = BASE_SPEED * multiplier;
                $('#speedLabel').text(`X${multiplier}`);
                if (pathNavigs) {
                    pathNavigs.setSpeed(speed);
                }
            }
            $('#speedSelect').on('change', function () {
                updateSpeedFromSelect();
            });
            /** 
             * 更新按钮状态
             * */
            function updateButtonStates() {

                //                 stop ：停止状态，start 之前或者 stop 之后处于该状态

                // moving ：巡航状态， start 或者 resume 之后处于该状态

                // pause ：暂停状态，pause 之后处于该状态
                const status = pathNavigs ? pathNavigs.getNaviStatus() : null;
                console.log('status===', status)
                let btnText = '开始';
                if (status === 'moving') {
                    btnText = '暂停';
                } else if (status === 'pause') {
                    btnText = '恢复';
                } else if (status === 'stop' || status === 'end') {
                    btnText = '重新开始'; // 轨迹结束或停止后显示“重新开始”
                }

                $('#btnControl').text(btnText);

                $('#btnControl').text(btnText);
            }

            // 绑定按钮点击事件
            $('#btnStart').on('click', function () {
                updateSpeedFromSelect(); // 确保开始前应用最新速度
                const navg = createNavg();
                if (navg) navg.start();
                updateButtonStates();
            });

            $('#btnPause').on('click', function () {
                if (pathNavigs) pathNavigs.pause();
                updateButtonStates();
            });

            $('#btnResume').on('click', function () {
                if (pathNavigs) pathNavigs.resume();
                updateButtonStates();
            });

            $('#btnStop').on('click', function () {
                if (pathNavigs) pathNavigs.stop();
                updateButtonStates();
            });

            $('#btnDestroy').on('click', function () {
                if (pathNavigs) pathNavigs.destroy();
                pathNavigs = null;
                updateButtonStates();
            });





            // 动态按钮控制
            $('#btnControl').on('click', function () {
                const navg = createNavg(); // 确保已创建导航实例
                const status = pathNavigs ? pathNavigs.getNaviStatus() : null;

                switch (status) {
                    case 'init': // 初始状态
                        updateSpeedFromSelect();
                        navg.start();
                        break;
                    case 'moving': // 正在移动
                        navg.pause();
                        break;
                    case 'pause': // 已暂停
                        navg.resume();
                        break;
                    case 'stop': // 已停止
                        navg.start();
                        break;
                    default: // 未初始化或已销毁
                        updateSpeedFromSelect();
                        navg.start();
                        break;
                }
                updateButtonStates();
            });








        })

    </script>
</body>

</html>